package com.crack.nga2.volley;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.crack.nga2.entity.Message;
import com.crack.nga2.utils.GlobalConst;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查看短消息请求
 * Created by Administrator on 2016/1/6.
 */
public class MessageRequest extends Request<List<Message>> {
    private Response.Listener<List<Message>> listener;

    public MessageRequest(int method, String url, Response.Listener<List<Message>> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headFields = new HashMap<>();
        headFields.put("Cookie", GlobalConst.Cookie);
        return headFields;
    }

    @Override
    protected Response<List<Message>> parseNetworkResponse(NetworkResponse response) {
        String json;
        try {
            json = new String(response.data, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Response.error(new VolleyError(e.getMessage()));
        }
        //去除无用数据
        json = json.substring(json.indexOf("{") + 1, json.lastIndexOf("}"));
        json = json.substring(json.indexOf("{") + 1, json.lastIndexOf("}"));
        json = json.substring(json.indexOf("{"));
        List<Message> list = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(json);
            Gson gson = new Gson();
            int rows = object.getInt("rowsPerPage");
            for (int i = 0; i < rows; i++) {
                JSONObject messageObject = object.getJSONObject(String.valueOf(i));
                Message message = gson.fromJson(messageObject.toString(), Message.class);
                list.add(message);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return Response.success(list, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(List<Message> response) {
        if (listener != null) {
            listener.onResponse(response);
        }
    }
}
